package com.jfshop.framework.copier;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import net.sf.cglib.beans.BeanCopier;
@SuppressWarnings("unchecked")
public abstract class BaseCopier<P, V> {
	
	private Class<P> pClass;
	private Class<V> vClass;
	
    BeanCopier copier2VO;
    BeanCopier copier2PO;
    
    /**
     * 构造函数
     * 进行初始化操作
     */
	public BaseCopier() { 
		Type genType = getClass().getGenericSuperclass();  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
        pClass = (Class<P>) params[0];
        vClass = (Class<V>) params[1];
        copier2VO  = BeanCopier.create(pClass, vClass, false);
        copier2PO  = BeanCopier.create(vClass,pClass, false);
	}
	
	/**
	 * PO 到 VO 的拷贝
	 * NOTICE: 同名不同类型的将不会被拷贝
	 * @param v  源VO
	 * @return   目标PO
	 */
	public P copy2po(V v) {
		if (v == null) return null;
		
		Object tragetBean;
		try {
			tragetBean = pClass.newInstance();
			copier2PO.copy(v, tragetBean, null);
			return (P) tragetBean;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
        return null;
	}
	
	/**
	 * PO 到 VO 的拷贝
	 * NOTICE: 同名不同类型的将不会被拷贝
	 * @param p  源PO
	 * @return   目标VO
	 */
	public V copy2vo(P p) {
		if (p == null) return null;
		
		Object tragetBean;
		try {
			tragetBean = vClass.newInstance();
			copier2VO.copy(p, tragetBean, null);
			return (V) tragetBean;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
    
}
